package com.foxchen.ddns.core;

import com.foxchen.ddns.config.DDNSConfig;
import com.foxchen.ddns.service.DomainUpdateDnsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DDNSAutoUpdate {
    @Resource
    private DDNSConfig ddnsConfig;
    @Resource
    private Map<String, DomainUpdateDnsService>  domainUpdateDnsServices;


    @PostConstruct
    public void init() {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(() -> {
            try {
                // 全部的配置
                List<DDNSConfig.Detail> allDomainMap = ddnsConfig.getAllDomainConfig();

                for (DDNSConfig.Detail detail : allDomainMap) {
                    long timeMillis = System.currentTimeMillis();
                    String domain = detail.getDomain();
                    log.info("ddns task execute begin,domain={}",domain);

                    DomainUpdateDnsService domainUpdateDnsService = domainUpdateDnsServices.get(detail.getDomainFrom());
                    if (domainUpdateDnsService == null) {
                        log.warn("unkown domain source:{},domain:{}", detail.getDomainFrom(),domain);
                        continue;
                    }

                    // 此域名更新dns
                    domainUpdateDnsService.updateDns(domain,detail);
                    log.info("ddns task execute end,domain={},consume time(ms)={}",domain,System.currentTimeMillis() - timeMillis);
                }
                TimeUnit.SECONDS.sleep(60);
            } catch (Exception e) {
                log.error("ddns task execute error", e);
            }
        }, 0, 30, TimeUnit.SECONDS);
    }

}
